import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { routerRedux } from 'dva/router';
import { fakeAccountLogin, getFakeCaptcha,tokenLogin } from './service';
import { getPageQuery, setAuthority } from './utils/utils';
import { setLoginInfo } from '../../../utils/BdHelper';
import { router } from 'umi';
import request from '@/utils/request';

export interface StateType {
  code?: number;
  type?: string;
  currentAuthority?: 'user' | 'guest' | 'admin';
  msg?: string;
}

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: StateType) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: StateType;
  effects: {
    tokenLogin:Effect;
    login: Effect;
    getCaptcha: Effect;    
  };
  reducers: {
    changeLoginStatus: Reducer<StateType>;
  };
}

const Model: ModelType = {
  namespace: 'userAndlogin',

  state: {
    code: undefined,
    msg: '',
    currentAuthority:'admin'
  },

  effects: {
    *tokenLogin({ payload }, { call, put }) {
      
      // tokenLogin(payload).then((res:any)=>{
      //   console.log(res)
      // })
      let token = localStorage.getItem('token')
      let email = localStorage.getItem('email')
      let feeRate = localStorage.getItem('feeRate')
      const response = yield call(tokenLogin, payload);
      if(response){
        yield put({
          type: 'changeLoginStatus',
          payload: response,
        });
      }else{
        router.push(`/token/login?token=${token}&email=${email}&feeRate=${feeRate}`)
      }
      // yield put({
      //   type: 'changeLoginStatus',
      //   payload: response,
      // });
      console.log('response', response)
      // Login successfully
      if (response&&response.code === 0) {
        console.log('response', response)
        setLoginInfo(response.data);
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params as { redirect: string };
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = redirect;
            return;
          }
        }
        yield put(routerRedux.replace(redirect || '/taskManagement/taskList'));
      }
    },

    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },

    *login({ payload }, { call, put }) {
      const response = yield call(fakeAccountLogin, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      
      // Login successfully
      yield put(routerRedux.replace( '/dashboard/analysis'));
      if (response.code === 0) {
        console.log('response', response)
        setLoginInfo(response.data);
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params as { redirect: string };
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = redirect;
            return;
          }
        }
        yield put(routerRedux.replace(redirect || '/dashboard/analysis'));
      }
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.data.currentAuthority);
      console.log('response-payload-->', payload)
      return {
        ...state,
        code: payload.code,
        type: payload.type || 'account',
        msg: payload.message
      };
    },
  },
};

export default Model;
